package concurrent;

import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 一个支持优先级排序的无界阻塞队列，进入队列的元素会按照优先级进行排序
 *
 * @author jack.wu
 * @since 2019/12/23 12:03
 */
public class PriorityBlockingQueueTest {

    static PriorityBlockingQueue<Msg> pushQueue = new PriorityBlockingQueue<>();

    static {
        new Thread(() -> {
            while (true) {
                Msg msg;
                try {
                    long startTime = System.currentTimeMillis();
                    msg = pushQueue.take();
                    TimeUnit.MILLISECONDS.sleep(500);
                    long endTime = System.currentTimeMillis();
                    System.out.println(String.format("[%s，%s，take耗时：%s，发送消息：%s]",
                            startTime, endTime, (endTime - startTime), msg));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static void pushMsg(Msg msg) {
        pushQueue.put(msg);
    }

    public static void main(String[] args) {
        for (int i = 5; i > 0; i--) {
            String msg = "消息" + i;
            pushMsg(new Msg(i, msg));
        }

    }

}

class Msg implements Comparable<Msg> {

    /*优先级*/
    private int priority;

    /*消息*/
    private String msg;

    public Msg(int priority, String msg) {
        this.priority = priority;
        this.msg = msg;
    }

    @Override
    public int compareTo(Msg o) {
        return Integer.compare(this.priority, o.priority);
    }

    @Override
    public String toString() {
        return "Msg{" +
                "priority=" + priority +
                ", msg='" + msg + '\'' +
                '}';
    }
}
